package com.feng.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.feng.dao.CompanyDao;
import com.feng.entity.Company;
import com.feng.service.CompanyService;
import com.feng.util.StringUtil;
import com.feng.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

/**
 * @author: 丰
 * @date: 2023/1/1 16:28
 */
@Service
public class CompanyServiceImpl implements CompanyService {

    @Autowired
    private CompanyDao companyDao;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Override
    public Object get() {
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        // 如果redis存在，就返回redis里面的值
        if (redisTemplate.hasKey("companyGet")){
           return opsForValue.get("companyGet");
        }
        Company company = companyDao.get();
        if (company != null){
            // 先将值设置到redis
            opsForValue.set("companyGet", JSONObject.toJSONString(ResultVo.success(company)));
            return ResultVo.success(company);
        }
        return ResultVo.failed();
    }

    @Override
    public ResultVo<Integer> update(Company company) {
        // 设置上班时间
        String[] workTime = company.getWorkTime().split("~");
        company.setWorkStartTime(workTime[0].trim());
        company.setWorkEndTime(workTime[1].trim());

        company.setUpdateTime(StringUtil.getStringDate());
        int result = companyDao.update(company);
        if (result > 0){
            // 更新完成之后，清空redis
            if (redisTemplate.hasKey("companyGet")){
                redisTemplate.delete("companyGet");
            }
            return ResultVo.success(result);
        }
        return ResultVo.failed();
    }
}
